<template>
  <Header/>
  <div class="article-publish-container">
    <!-- 顶部标题 -->
    <!--    <div class="publish-header">
          <h1 class="publish-title">发布新文章</h1>
          <div class="publish-steps">
            <el-steps :active="1" align-center>
              <el-step title="编辑内容" />
              <el-step title="设置信息" />
              <el-step title="发布完成" />
            </el-steps>
          </div>
        </div>-->

    <!-- 主内容区 -->
    <div class="publish-content">
      <!-- 左侧表单卡片 -->
      <el-card class="settings-card">
        <div class="card-header">
          <el-icon class="card-icon">
            <Document/>
          </el-icon>
          <span class="card-title">文章设置</span>
          <!-- 添加Deepseek触发按钮 -->
          <el-button
              type="primary"
              size="small"
              @click="drawerVisible = true"
              class="deepseek-btn"
          >
            <el-icon>
              <Search/>
            </el-icon>
            创作助手
          </el-button>
        </div>

        <!-- 文章标题 -->
        <div class="form-item">
          <div class="form-label">
            <el-icon>
              <Edit/>
            </el-icon>
            <span>文章标题</span>
          </div>
          <el-input
              v-model="input1"
              placeholder="请输入文章标题"
              class="elegant-input"
              size="large"
          />
        </div>

<!-- 文章分类 -->
<div class="form-item">
  <div class="form-label">
    <el-icon>
      <Folder/>
    </el-icon>
    <span>文章分类</span>
  </div>
  <el-select
      v-model="value"
      placeholder="请选择分类"
      class="elegant-select"
      size="large"
      multiple
      collapse-tags-tooltip
  >
    <el-option
        v-for="item in options"
        :key="item.value"
        :label="item.label"
        :value="item.value"
    />
  </el-select>
</div>


        <!-- 封面图上传 -->
        <div class="form-item">
          <div class="form-label">
            <el-icon>
              <Picture/>
            </el-icon>
            <span>封面图片</span>
          </div>
          <div class="upload-wrapper">
            <el-upload
                action="http://localhost:8888/upload"
                list-type="picture-card"
                :auto-upload="true"
                :on-success="handleUploadSuccess"
                class="elegant-upload"
            >
              <el-icon class="upload-icon">
                <Plus/>
              </el-icon>
              <template #file="{ file }">
                <div class="file-container">
                  <img class="file-img" :src="file.url" alt="封面图"/>
                  <div class="file-actions">
                    <el-tooltip content="预览" placement="top">
                      <div class="action-btn" @click="handlePictureCardPreview(file)">
                        <el-icon>
                          <ZoomIn/>
                        </el-icon>
                      </div>
                    </el-tooltip>
                    <el-tooltip content="下载" placement="top">
                      <div class="action-btn" @click="handleDownload(file)">
                        <el-icon>
                          <Download/>
                        </el-icon>
                      </div>
                    </el-tooltip>
                    <el-tooltip content="删除" placement="top">
                      <div class="action-btn" @click="handleRemove(file)">
                        <el-icon>
                          <Delete/>
                        </el-icon>
                      </div>
                    </el-tooltip>
                  </div>
                </div>
              </template>
            </el-upload>
          </div>
        </div>

        <!-- 发布设置 -->
        <div class="form-item">
          <div class="form-label">
            <el-icon>
              <Lock/>
            </el-icon>
            <span>发布设置</span>
          </div>
          <div class="publish-settings">
            <el-switch
                v-model="publicStatus"
                inline-prompt
                active-text="公开"
                inactive-text="私密"
                active-value="公开"
                inactive-value="隐藏"
                size="large"
                style="--el-switch-on-color: #5cb85c; --el-switch-off-color: #d9534f"
            />
            <span class="setting-tip">公开文章将对所有用户可见</span>
          </div>
        </div>
      </el-card>

      <!-- 右侧编辑器 -->
      <div class="editor-wrapper">
        <div class="editor-header">
          <el-icon>
            <Notebook/>
          </el-icon>
          <span>文章内容</span>
        </div>
        <v-md-editor
            v-model="content"
            height="calc(100vh - 220px)"
            class="elegant-editor"
            left-toolbar="undo redo clear | h bold italic strikethrough quote | ul ol table hr | link image code"
            right-toolbar="preview toc fullscreen"
        />
      </div>
    </div>

    <!-- 底部操作栏 -->
    <div class="publish-footer">
      <el-button class="save-draft" size="large" @click="saveDraft">
        <el-icon>
          <DocumentAdd/>
        </el-icon>
        保存草稿
      </el-button>
      <el-button
          type="primary"
          size="large"
          class="publish-btn"
          @click="submit"
      >
        <el-icon>
          <Promotion/>
        </el-icon>
        {{ isEditMode ? '更新文章' : '立即发布' }}
      </el-button>
    </div>

    <!-- 图片预览对话框 -->
    <el-dialog v-model="dialogVisible" class="image-preview-dialog">
      <img class="preview-image" :src="dialogImageUrl" alt="预览图"/>
    </el-dialog>
    <!-- Deepseek侧边抽屉 -->
    <el-drawer
        v-model="drawerVisible"
        title="Nova AI 创作助手"
        :direction="direction"
        size="40%"
        class="deepseek-drawer"
    >
      <template #header>
        <div class="drawer-header">
          <span>Nova AI 创作助手</span>
          <el-button
              type="danger"
              size="small"
              @click="clearMessages"
              class="clear-btn"
          >
            <el-icon>
              <Delete />
            </el-icon>
            清空记录
          </el-button>
        </div>
      </template>
      <div class="deepseek-content">
        <!-- 聊天消息区域 -->
        <div class="chat-container">
          <div v-for="(message, index) in messages" :key="index" class="message" :class="message.role">
            <div class="message-header">
              <el-icon v-if="message.role === 'user'">
                <User/>
              </el-icon>
              <img
                  v-else
                  src="@/assets/icon/deepseek.svg"
                  alt="DeepSeek"
                  class="ai-avatar"
              />
              <span>{{ message.role === 'user' ? '你' : 'Nova 智能助手' }}</span>
            </div>

            <div
                v-if="message.renderedHtml"
                class="message-content"
                v-html="message.renderedHtml"
            ></div>
            <div v-else class="message-content">{{ message.content }}</div>
          </div>
          <div v-if="isLoading" class="loading-indicator">
            <el-icon class="is-loading">
              <Loading/>
            </el-icon>
            <span>思考中...</span>
          </div>
          <div v-if="errorMessage" class="error-message">
            <el-icon>
              <Warning/>
            </el-icon>
            <span>{{ errorMessage }}</span>
          </div>
        </div>

        <!-- 输入区域 -->
        <div class="input-area">
          <el-input
              v-model="userInput"
              placeholder="输入你的问题..."
              class="chat-input"
              @keyup.enter="sendMessage"
              :disabled="isLoading"
          >
            <template #append>
              <el-button
                  type="primary"
                  @click="sendMessage"
                  :disabled="!userInput.trim() || isLoading"
              >
                <el-icon>
                  <Promotion/>
                </el-icon>
              </el-button>
            </template>
          </el-input>
        </div>
      </div>
    </el-drawer>

  </div>
</template>

<script setup lang="ts">
import {ref, onMounted} from 'vue'
import {
  Document,
  Edit,
  Folder,
  Picture,
  Lock,
  Notebook,
  DocumentAdd,
  Promotion,
  Plus,
  ZoomIn,
  Download,
  Delete, User, Search, Loading, Warning
} from '@element-plus/icons-vue'
import type {UploadFile} from 'element-plus'
import request from '@/api/request'
import {ElMessage, ElMessageBox} from 'element-plus'

import OpenAI from 'openai'
import Header from "@/components/Header.vue"
import VueMarkdownEditor, {xss} from '@kangc/v-md-editor'
import createLineNumbertPlugin from '@kangc/v-md-editor/lib/plugins/line-number/index'
import createCopyCodePlugin from '@kangc/v-md-editor/lib/plugins/copy-code/index'
import {useRoute} from "vue-router";
import router from "@/router";


VueMarkdownEditor.use(createCopyCodePlugin())
// 初始化Markdown编辑器插件
VueMarkdownEditor.use(createLineNumbertPlugin())
VueMarkdownEditor.use(createCopyCodePlugin())

// 初始化Deepseek
interface Message {
  role: 'user' | 'assistant'
  content: string
  renderedHtml?: string
}

// 初始化OpenAI客户端
const openai = new OpenAI({
  apiKey: 'sk-c00c6676be584ace93cbb132de167f44',
  baseURL: 'https://api.deepseek.com/v1',
  dangerouslyAllowBrowser: true
})

// 响应式数据
const drawerVisible = ref(false)
const direction = ref('rtl')
const userInput = ref('')
const isLoading = ref(false)
const errorMessage = ref('')
const messages = ref<Message[]>([
  {
    role: 'assistant',
    content: '你好，我是我是Nova 创作助手，您可以像聊天一样与我对话，并提出任何与代码和编程相关的问题。例如：\n\n- 如何优化这段代码？\n- 请解释这个函数的作用\n- 帮我生成一个表单组件\n- 这段代码有什么问题？\n\n我会尽力为您提供帮助！',
    renderedHtml: VueMarkdownEditor.vMdParser.themeConfig.markdownParser.render(
        '你好，我是Nova 创作助手，您可以像聊天一样与我对话，并提出任何与代码和编程相关的问题。例如：\n\n- 如何优化这段代码？\n- 请解释这个函数的作用\n- 帮我生成一个表单组件\n- 这段代码有什么问题？\n\n我会尽力为您提供帮助！'
    )
  }
])

const clearMessages = () => {
  messages.value = [
    {
      role: 'assistant',
      content: '你好，我是Nova 创作助手，您可以像聊天一样与我对话，并提出任何与代码和编程相关的问题。例如：\n\n- 如何优化这段代码？\n- 请解释这个函数的作用\n- 帮我生成一个表单组件\n- 这段代码有什么问题？\n\n我会尽力为您提供帮助！',
      renderedHtml: VueMarkdownEditor.vMdParser.themeConfig.markdownParser.render(
          '你好，我是Nova 创作助手，您可以像聊天一样与我对话，并提出任何与代码和编程相关的问题。例如：\n\n- 如何优化这段代码？\n- 请解释这个函数的作用\n- 帮我生成一个表单组件\n- 这段代码有什么问题？\n\n我会尽力为您提供帮助！'
      )
    }
  ]
  ElMessage.success('聊天记录已清空')
}

const sendMessage = async () => {
  if (!userInput.value.trim() || isLoading.value) return

  const userMessage = userInput.value
  messages.value.push({role: 'user', content: userMessage})
  userInput.value = ''
  isLoading.value = true
  errorMessage.value = ''

  try {
    // 使用OpenAI SDK调用DeepSeek API
    const completion = await openai.chat.completions.create({
      model: "deepseek-chat",
      messages: messages.value.map(msg => ({
        role: msg.role,
        content: msg.content
      })),
      temperature: 0.7,
      max_tokens: 2000
    })

    const aiMessage = completion.choices[0]?.message?.content
    if (aiMessage) {
      const renderedHtml = VueMarkdownEditor.vMdParser.themeConfig.markdownParser.render(aiMessage)
      messages.value.push({
        role: 'assistant',
        content: aiMessage,
        renderedHtml: xss.process(renderedHtml)
      })
    } else {
      throw new Error('未收到有效回复')
    }
  } catch (error) {
    console.error('API调用错误:', error)
    errorMessage.value = error instanceof Error ? error.message : '请求发生错误'
    ElMessage.error('请求发生错误: ' + errorMessage.value)
  } finally {
    isLoading.value = false
  }
}

interface Option {
  value: number | any
  label: string | any
}

// 数据定义
const content = ref('')
const input1 = ref('')
// 数据定义
const value = ref<number[]>([]);

const publicStatus = ref('公开')
const dialogImageUrl = ref('')
const dialogVisible = ref(false)
const disabled = ref(false)
const options = ref<Option[]>([])
const fileList = ref<UploadFile[]>([])
const route = useRoute();
const isEditMode = ref(false);
const articleId = ref('');

// 方法定义
const handleRemove = (file: UploadFile) => {
  fileList.value = fileList.value.filter(item => item.uid !== file.uid)
}

const handlePictureCardPreview = (file: UploadFile) => {
  if (file.url) dialogImageUrl.value = file.url
  dialogVisible.value = true
}


const handleUploadSuccess = (file: UploadFile) => {
  fileList.value.push(file)
}

const handleDownload = (file: UploadFile) => {
  console.log(file)
}

const getCategory = async () => {
  try {
    const response = await request.get('/category/getCategory')
    options.value = response.data.map((item: any) => ({
      value: item.id,
      label: item.categoryName
    }))
  } catch (error) {
    console.error('获取文章类别失败:', error)
  }
}

const saveDraft = () => {
  ElMessage.info('草稿已保存')
}

const submit = async () => {
  const articleData = {
    id: isEditMode.value ? articleId.value : undefined,
    title: input1.value,
    categoryId: value.value,
    state: publicStatus.value,
    content: content.value,
    coverImg: fileList.value[0]?.data
  };

  try {
    let response;
    if (isEditMode.value) {
      response = await request.put(
          `/article/editArticle?categoryId=${articleData.categoryId}`,
          articleData
      );
    } else {
      response = await request.post(
          `/article/addarticle?categoryId=${articleData.categoryId}`,
          articleData
      );
    }
    ElMessage.success(response.message);
    resetForm();
    router.push('/MyInfo');
  } catch (error: any) {
    ElMessage.error(error.message);
    console.error(isEditMode.value ? '编辑文章失败' : '发布文章失败', error);
  }
};

const resetForm = () => {
  input1.value = ''
  value.value = []
  publicStatus.value = '公开'
  content.value = ''
  fileList.value = []
}

onMounted(() => {
  getCategory()

  if (route.query.id) {
    isEditMode.value = true;
    articleId.value = route.query.id as string;
    input1.value = route.query.title as string;
    content.value = route.query.content as string;
    // 其他需要初始化的字段
  }
})
</script>

<style scoped>
.article-publish-container {
  max-width: 1400px;
  margin: 80px auto;
  padding: 0 20px 40px;
  height: 73vh;
  color: #333;
}

.publish-header {
  margin: 30px 0 40px;
  text-align: center;
}

.publish-title {
  font-size: 28px;
  font-weight: 600;
  color: #2c3e50;
  margin-bottom: 20px;
  letter-spacing: 1px;
}

.publish-steps {
  max-width: 800px;
  margin: 0 auto;
}

.publish-content {
  display: grid;
  grid-template-columns: 360px 1fr;
  gap: 24px;
  margin-bottom: 30px;
}

.settings-card {
  border-radius: 12px;
  box-shadow: 0 6px 18px rgba(0, 0, 0, 0.06);
  border: none;
  padding: 20px;
}

.card-header {
  display: flex;
  align-items: center;
  margin-bottom: 25px;
  padding-bottom: 15px;
  border-bottom: 1px solid #f0f2f5;
}

.card-icon {
  font-size: 22px;
  color: var(--el-color-primary);
  margin-right: 10px;
}

.card-title {
  font-size: 18px;
  font-weight: 600;
  color: #2c3e50;
}

.form-item {
  margin-bottom: 28px;
}

.form-label {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
  font-size: 15px;
  color: #555;
}

.form-label .el-icon {
  margin-right: 8px;
  font-size: 18px;
}

.elegant-input,
.elegant-select {
  width: 100%;
}

.upload-wrapper .elegant-upload .el-upload {
  width: 120px;
  height: 120px;
  border-radius: 8px;
  border: 1px dashed var(--el-border-color);
  transition: all 0.3s;
}

.upload-wrapper .elegant-upload .el-upload:hover {
  border-color: var(--el-color-primary);
}

.upload-wrapper .upload-icon {
  font-size: 28px;
  color: #8c939d;
  transition: all 0.3s;
}

.upload-wrapper .elegant-upload:hover .upload-icon {
  color: var(--el-color-primary);
}

.file-container {
  position: relative;
  width: 100%;
  height: 100%;
  border-radius: 8px;
  overflow: hidden;
}

.file-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.file-actions {
  position: absolute;
  display: flex;
  justify-content: center;
  align-items: center;
  inset: 0;
  background-color: rgba(0, 0, 0, 0.5);
  opacity: 0;
  transition: opacity 0.3s;
}

.file-actions .action-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 32px;
  height: 32px;
  margin: 0 6px;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 50%;
  color: white;
  cursor: pointer;
  transition: all 0.2s;
}

.file-actions .action-btn .el-icon {
  font-size: 16px;
}

.file-actions .action-btn:hover {
  background: rgba(255, 255, 255, 0.3);
  transform: scale(1.1);
}

.file-container:hover .file-actions {
  opacity: 1;
}

.publish-settings {
  display: flex;
  align-items: center;
}

.publish-footer {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: white;
  padding: 15px 20px;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
  z-index: 1000;
  display: flex;
  justify-content: center;
  gap: 20px;
}

.publish-settings .setting-tip {
  margin-left: 12px;
  font-size: 13px;
  color: #999;
}

.editor-wrapper {
  background: white;
  border-radius: 12px;
  box-shadow: 0 6px 18px rgba(0, 0, 0, 0.06);
  overflow: hidden;
}

.editor-header {
  display: flex;
  align-items: center;
  padding: 16px 20px;
  background: white;
  border-bottom: 1px solid #f0f2f5;
}

.editor-header .el-icon {
  font-size: 20px;
  color: var(--el-color-primary);
  margin-right: 10px;
}

.editor-header span {
  font-size: 16px;
  font-weight: 600;
  color: #2c3e50;
}

.elegant-editor {
  border-radius: 0 0 12px 12px;
}

.elegant-editor .v-md-editor {
  border: none;
}

.publish-footer {
  display: flex;
  justify-content: center;
  gap: 20px;
  margin-top: 30px;
}

.publish-footer .el-button {
  padding: 0 30px;
  font-size: 16px;
  letter-spacing: 1px;
  transition: all 0.3s;
}

.publish-footer .el-button .el-icon {
  margin-right: 8px;
}

.save-draft {
  border-color: #ddd;
  color: #666;
}

.save-draft:hover {
  border-color: #bbb;
  color: #333;
}

.publish-btn {
  background: linear-gradient(135deg, #6e8efb, #4a6cf7);
  border: none;
  box-shadow: 0 4px 12px rgba(74, 108, 247, 0.3);
}

.publish-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 16px rgba(74, 108, 247, 0.4);
}

.image-preview-dialog .preview-image {
  max-width: 100%;
  max-height: 80vh;
  display: block;
  margin: 0 auto;
  border-radius: 8px;
}

.deepseek-btn {
  margin-left: auto;
  background: linear-gradient(135deg, #6e8efb, #4a6cf7);
}

.deepseek-drawer {
  --el-drawer-padding-primary: 20px;
}

.deepseek-content {
  padding: 20px;
  height: 100%;
}

.deepseek-drawer {
  --el-drawer-padding-primary: 0;
}

.deepseek-content {
  display: flex;
  flex-direction: column;
  height: 100%;
  padding: 20px;
}

.chat-container {
  flex: 1;
  overflow-y: auto;
  padding: 10px;
  margin-bottom: 20px;
  border: 1px solid #ebeef5;
  border-radius: 8px;
  background-color: #f8f9fa;
}

.message {
  margin-bottom: 20px;
  padding: 12px 16px;
  border-radius: 8px;
  background-color: white;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.message-header {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
  font-weight: bold;
  color: #606266;
}

.message-header .el-icon {
  margin-right: 8px;
}

.message-content {
  line-height: 1.6;
  font-size: 0.3em; /* 调整为原来的30% */
}

.message-content :deep(pre) {
  background-color: #f6f8fa;
  padding: 12px;
  border-radius: 6px;
  overflow-x: auto;
}

.message-content :deep(code) {
  font-family: 'Courier New', Courier, monospace;
  background-color: #f6f8fa;
  padding: 2px 4px;
  border-radius: 3px;
}

.user {
  border-left: 4px solid #409eff;
}

.assistant {
  border-left: 4px solid #67c23a;
}

.loading-indicator {
  display: flex;
  align-items: center;
  padding: 12px;
  color: #909399;
}

.loading-indicator .el-icon {
  margin-right: 8px;
  animation: rotating 2s linear infinite;
}

.error-message {
  display: flex;
  align-items: center;
  padding: 12px;
  color: #f56c6c;
}

.error-message .el-icon {
  margin-right: 8px;
}

.input-area {
  padding: 10px 0;
}

.chat-input {
  border-radius: 20px;
}

.chat-input :deep(.el-input__inner) {
  font-size: 1.0em;
}

.message-header {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
  font-weight: bold;
  color: #606266;
  font-size: 0.3em;
}

.message-header .el-icon,
.message-header img.ai-avatar {
  margin-right: 8px;
  width: 30px;
  height: 30px;
}

.ai-avatar {
  border-radius: 50%;
}


.loading-indicator,
.error-message {
  font-size: 0.3em;
}

.chat-input :deep(.el-input-group__append) {
  border-radius: 0 20px 20px 0;
}
.drawer-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.clear-btn {
  margin-left: auto;
}
@keyframes rotating {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
</style>
